package com.leo.base.db;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @ClassName DBUtil
 * @Description
 * @Author wangss
 * @date 2020.09.15 18:00
 * @Version 1.0
 */
@Slf4j
public class ReflectionUtil {

    /**
     * 获取分片值
     *
     * @param parameterNamesLength
     * @param args
     * @param shardingField
     * @param parameterNames
     * @return
     */
    public static String getShardingFieldValue(int parameterNamesLength, Object[] args, String shardingField, String[] parameterNames) {
        for (int i = 0; i < parameterNamesLength; i++) {
            Object object = args[i];
            if (null == object) {
                continue;
            }
            if (object instanceof String || object instanceof Integer) {
                if (shardingField.equals(parameterNames[i])) {
                    return String.valueOf(object);
                }
            } else if (object instanceof Map) {
                return String.valueOf(((Map) object).get(shardingField));
            } else {
                // 对象
                return getshardingFieldValueByObject(object, shardingField);
            }
        }
        return null;
    }

    private static String getshardingFieldValueByObject(Object object, String shardingField) {
        try {
            Field declaredField = object.getClass().getDeclaredField(shardingField);
            if (null == declaredField) {
                declaredField = object.getClass().getSuperclass().getDeclaredField(shardingField);
            }

            if (null == declaredField) {
                return null;
            }
            declaredField.setAccessible(true);
            return String.valueOf(declaredField.get(object));
        } catch (NoSuchFieldException e) {
            log.error("getshardingFieldValueByObject error [{}]", e.getMessage());
            return null;
        } catch (IllegalAccessException e) {
            log.error("getshardingFieldValueByObject error [{}]", e.getMessage());
            return null;
        }
    }
}
